package com.sunleader.netboot.module.machine.util;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Slf4j
public class SSHTool {
    public static void reboot(String ip,String pwd) throws JSchException, IOException {
        Session session = null;
        try {
            JSch jsch = new JSch();
            session  = jsch.getSession("root", ip, 22);
            session.setPassword(pwd);
            // 使用密码登录 禁止使用秘钥登录(默认先使用秘钥，失败后使用密码，耗时严重)
            session.setConfig("StrictHostKeyChecking", "no");
            session.setConfig("PreferredAuthentications", "password");

            // 连接超时
            session.connect(5000);
            Channel channel = session.openChannel("exec");
            ChannelExec exec = (ChannelExec) channel;
            // 返回结果流（命令执行错误的信息通过getErrStream获取）

            exec.setCommand("reboot");
            exec.connect();
            try {
                // 开始获得SSH命令的结果
                while (true) {
                    InputStream inputStream = exec.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    String buf;
                    // 此处是对结果进行封装，封装成自己想要的样子，我这里是map
                    while ((buf = reader.readLine()) != null) {
                        String gbk = new String(buf.getBytes("gbk"), StandardCharsets.UTF_8);
                        log.info(gbk);
                    }

                    // 对错误的处理结果进行处理
                    InputStream errorStream = exec.getErrStream();
                    if (errorStream.available() > 0) {
                        byte[] tmp = new byte[1024];
                        int i = errorStream.read(tmp, 0, 1024);
                        if (i < 0) {
                            break;
                        }

                        log.error(new String(tmp, 0, i));
                        //Throw.bizStatusException(new String(tmp, 0, i));
                    }
                    if (exec.isClosed()) {
                        break;
                    }
                }
            } finally {
                //关闭连接
                channel.disconnect();
            }
        }finally {
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
}
